package servlet;

import pojo.Book;
import pojo.BookPage;
import pojo.Category;
import service.BookService;
import service.BookServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Tiler on 2020/11/5
 */
public class GetAllBooks extends HttpServlet {
    private BookService bookService = new BookServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");

        Map<String, Object> params = new HashMap<>();

        String page = req.getParameter("page");
        String size = req.getParameter("size");

        Integer pid = (page==null)? 1 : Integer.parseInt(page);
        Integer num = (size==null)? 5 : Integer.parseInt(size);

        params.put("page", pid);
        params.put("size", num);

        BookPage bookPage = bookService.getAllBooks(params);

        for (Book book : bookPage.getBookList()) {
            List<Category> list = bookService.getCategoriesByBid(book.getBookId());

            book.setCategories(list);
        }

        req.setAttribute("bookPage", bookPage);

        req.getRequestDispatcher("all_books.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
